layui.use(['table', 'admin', 'ax', 'func', 'laypage', 'layer'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laypage = layui.laypage;
    var layer = layui.layer;

    /**
     * 数据库列表管理
     */
    var Dblist = {
        tableId: "dblistTable"
    };

    /**
     * 初始化表格的列
     */
    Dblist.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'id'},
            {field: 'dbName', sort: true, title: '数据库名称'},
            {field: 'dbUrl', sort: true, title: '数据库地址'},
            {field: 'dbDescribe', sort: true, title: '数据库描述'},
            {field: 'state', sort: true, title: '状态'},
            {field: 'revision', sort: true, title: '乐观锁'},
            {field: 'createdBy', sort: true, title: '创建人'},
            {field: 'createdTime', sort: true, title: '创建时间'},
            {field: 'updatedBy', sort: true, title: '更新人'},
            {field: 'updatedTime', sort: true, title: '更新时间'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 弹出添加对话框
     */
    Dblist.openAddDlg = function () {
        func.open({
            title: '',
            content: Feng.ctxPath + '/dblist/add',
            tableId: Dblist.tableId
        });
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    Dblist.openEditDlg = function (id) {
        layer.open({
            title: '',
            type: 2,
            area: ['60%', '60%'],
            content: Feng.ctxPath + '/dblist/edit?id=' + id,
            tableId: Dblist.tableId,
            end: function () {
                getPage()
            }
        });
    };


    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    Dblist.onDeleteItem = function (id) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/dblist/delete", function (id) {
                Feng.success("删除成功!");
                // location.reload();
                // table.reload(Dblist.tableId);
                getPage();
            }, function (id) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Dblist.tableId,
        url: Feng.ctxPath + '/dblist/list',
        page: true,
        height: "full-158",
        cellMinWidth: 100,
        cols: Dblist.initColumn()
    });


    // 添加按钮点击事件
    $('#btnAdd').click(function () {

        Dblist.openAddDlg();

    });

    // 工具条点击事件
    table.on('tool(' + Dblist.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Dblist.openEditDlg(data);
        } else if (layEvent === 'delete') {
            Dblist.onDeleteItem(data);
        }
    });

    /**
     * 点击修改或删除跳转界面
     */

    $("#row").on("click", "#edit", function () {
        var id = $(this).parent().parent().parent().attr("id")
        var ajax = new $ax(Feng.ctxPath + "/dblist/list?id=" + id)
        var result = ajax.start();
        if (result.data[0].state == 0) {
            Feng.error("异常数据库不能进行修改")
            return
        }
        $("#dbName").val('');
        Dblist.openEditDlg(id);
    })

    $("#row").on("click", "#delete", function () {
        var id = $(this).parent().parent().parent().attr("id")
        $("#dbName").val('');
        Dblist.onDeleteItem(id);
    })


    /**
     * 获取数据库详情
     */

    $("#row").on("click", "#dbDetails", function () {
        var id = $(this).parent().attr("id")
        // console.log(id)
        //通过id查询到数据库servicelist的id
        var ajax = new $ax(Feng.ctxPath + "/dblist/list?id=" + id)
        var result = ajax.start();
        if (result.data[0].state == 0) {
            Feng.error("异常数据库不能查看详情")
            return
        }
        // console.log(result.data[0].serviceListId)
        window.location.href = Feng.ctxPath + "/dblist/details?id=" + result.data[0].serviceListId;
    })


    /**
     * 分页
     */
    function getPage(res) {
        var data = {};
        if (res != null && res != '') {
            data = res;
        }
        if ($("#dbName").val() == '') {
            $.get(Feng.ctxPath + "/dblist/list", data, function (res) {
                laypage.render({
                    elem: 'paging' //注意，这里的 test1 是 ID，不用加 # 号
                    , count: res.count
                    , layout: ['count', 'prev', 'page', 'next', 'skip']
                    , limit: 9
                    , jump: function (obj) {
                        // console.log(data);
                        // console.log(obj.curr)
                        getMydata(obj, data);
                    }
                });
            });
        } else {
            $.get(Feng.ctxPath + "/dblist/list?dbName=" + $("#dbName").val(), data, function (res) {
                laypage.render({
                    elem: 'paging' //注意，这里的 test1 是 ID，不用加 # 号
                    , count: res.count
                    , layout: ['count', 'prev', 'page', 'next', 'skip']
                    , limit: 9
                    , jump: function (obj) {
                        // console.log(data);
                        // console.log(obj.curr)
                        getSearchMydata(obj, data);
                    }
                });
            });
        }
    }

    function getDb() {
        $("#start").append("<div id='db' class='layui-row'></div>")
    }

    /**
     * 遍历生成数据
     * @param obj
     * @param mydata
     * @returns {boolean}
     */

    function getMydata(obj, mydata) {
        var pages = '';
        var limit = 9;
        var searchdata = {};
        if (obj != null && obj != '') {
            pages = obj.curr == '' ? '' : obj.curr;
            limit = obj.limit == '' ? '' : obj.limit;
        }
        if (mydata != '' && mydata != null) {
            searchdata = mydata;
        }
        // console.log(obj);
        $.get(Feng.ctxPath + "/dblist/list?page=" + pages + "&limit=" + limit, searchdata, function (obj) {
            // console.log(obj)
            $("#db").empty();
            for (var i = 0; i < obj.data.length; i++) {
                var val = obj.data[i];
                var color = "";
                if (val.state == 1) {
                    color = "greenyellow"
                } else if (val.state == 0) {
                    color = "red"
                }
                var a = '<div id="' + val.id + '" style="height: 165px;border-radius: 4px;margin-top: 25px;border: 1px solid gainsboro" class="layui-col-sm3 layui-col-md3 layui-col-lg3 layui-col-sm-offset1 layui-col-md-offset1 layui-col-lg-offset1">';
                a += ' <div class="layui-row">';
                a += '<div class="layui-col-sm1 layui-col-md1 layui-col-lg1">'
                a += '<div style="background-color: ' + color + ';border-radius: 10px;height: 13px;width: 13px;border: 1px solid grey;margin-top: 9px;margin-left: 9px"></div>'
                a += ' </div>'
                a += '<div class="layui-col-md6 layui-col-sm6 layui-col-lg6 layui-col-md-offset1 layui-col-sm-offset1 layui-col-lg-offset1">'
                a += '<h5  style="margin-top: 7px">' + val.dbName + '</h5>'
                a += '</div>'
                a += '<div class="layui-col-sm4 layui-col-md4 layui-col-lg4">'
                a += '<a class="layui-btn layui-btn-normal layui-btn-xs layui-icon" lay-event="edit" style="margin-top: 6px;border-radius: 5px;height: 19px" id="edit"> &nbsp;&#xe642;&nbsp; </a>'
                a += '<a class="layui-btn layui-btn-normal layui-btn-xs layui-icon" lay-event="delete" style="margin-top: 6px;border-radius: 5px;height: 19px" id="delete"> &nbsp;&#xe640;&nbsp; </a>'
                a += '</div>'
                a += '</div>'
                a += ' <div class="layui-row">'
                a += '<div class="layui-col-md9 layui-col-md-offset2 layui-col-sm9 layui-col-sm-offset2 layui-col-lg9 layui-col-lg-offset2">'
                a += '<div style="height: 90px;word-wrap: break-word;word-break: break-all;overflow: hidden;margin-top: 10px" class="layui-col-sm12 layui-col-md12 layui-col-lg12">'
                a += '<h5>数据库描述:' + val.dbDescribe + '</h5>'
                a += '</div>'
                a += '</div>'
                a += '</div>'
                a += '<div class="layui-row" id="dbDetails" style="margin-top: 5px;cursor:pointer">'
                a += '<div class="layui-col-md3 layui-col-md-offset9 layui-col-sm3 layui-col-sm-offset9 layui-col-lg3 layui-col-lg-offset9">' + val.dbMemory + '</div>'
                a += '</div>'
                a += '</div>'
                $("#db").append(a)
            }
        })
        return false;
    }


    function getSearchMydata(obj, mydata) {
        var pages = 1;
        var limit = 9;
        var searchdata = {};
        if (obj != null && obj != '') {
            pages = obj.curr == '' ? '' : obj.curr;
            limit = obj.limit == '' ? '' : obj.limit;
        }
        if (mydata != '' && mydata != null) {
            searchdata = mydata;
        }
        // console.log(obj);
        $.get(Feng.ctxPath + "/dblist/list?page=" + pages + "&limit=" + limit + '&dbName=' + $("#dbName").val(), searchdata, function (obj) {
            // console.log(obj)
            $("#db").empty();
            for (var i = 0; i < obj.data.length; i++) {
                var val = obj.data[i];
                var color = "";
                if (val.state == 1) {
                    color = "greenyellow"
                } else if (val.state == 0) {
                    color = "red"
                }
                var a = '<div style="height: 165px;border-radius: 4px;margin-top: 25px;border: 1px solid gainsboro" class="layui-col-sm3 layui-col-md3 layui-col-lg3 layui-col-sm-offset1 layui-col-md-offset1 layui-col-lg-offset1">';
                a += ' <div class="layui-row" id="' + val.id + '">';
                a += '<div class="layui-col-sm1 layui-col-md1 layui-col-lg1">'
                a += '<div style="background-color: ' + color + ';border-radius: 10px;height: 13px;width: 13px;border: 1px solid grey;margin-top: 9px;margin-left: 9px"></div>'
                a += ' </div>'
                a += '<div class="layui-col-md6 layui-col-sm6 layui-col-lg6 layui-col-md-offset1 layui-col-sm-offset1 layui-col-lg-offset1">'
                a += '<h5  style="margin-top: 7px">' + val.dbName + '</h5>'
                a += '</div>'
                a += '<div class="layui-col-sm4 layui-col-md4 layui-col-lg4">'
                a += '<a class="layui-btn layui-btn-normal layui-btn-xs layui-icon" lay-event="edit" style="margin-top: 6px;border-radius: 5px;height: 19px" id="edit"> &nbsp;&#xe642;&nbsp; </a>'
                a += '<a class="layui-btn layui-btn-normal layui-btn-xs layui-icon" lay-event="delete" style="margin-top: 6px;border-radius: 5px;height: 19px" id="delete"> &nbsp;&#xe640;&nbsp; </a>'
                a += '</div>'
                a += '</div>'
                a += ' <div class="layui-row">'
                a += '<div class="layui-col-md9 layui-col-md-offset2 layui-col-sm9 layui-col-sm-offset2 layui-col-lg9 layui-col-lg-offset2">'
                a += '<div style="height: 90px;word-wrap: break-word;word-break: break-all;overflow: hidden;margin-top: 10px" class="layui-col-sm12 layui-col-md12 layui-col-lg12">'
                a += '<h5>数据库描述:' + val.dbDescribe + '</h5>'
                a += '</div>'
                a += '</div>'
                a += '</div>'
                a += '<div class="layui-row" id="dbDetails" style="margin-top: 5px;cursor:pointer">'
                a += '<div class="layui-col-md3 layui-col-md-offset9 layui-col-sm3 layui-col-sm-offset9 layui-col-lg3 layui-col-lg-offset9">' + val.dbMemory + '</div>'
                a += '</div>'
                a += '</div>'
                $("#db").append(a)
            }
        })
        return false;
    }


    /**
     * 查询
     */
    $("#searchDatabase").click(function () {
        getPage()
    })


    /**
     * 渲染div
     */
    $(function () {

        // getMydata();
        getPage();
        getDb();

    });
});
